<?php

namespace app\api\controller;

use app\admin\model\Collect as ModelCollect;
use app\admin\model\post\Post;
use app\common\controller\Api;

class Collect extends Api
{

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];
    /**
     * 获取收藏列表
     */
    public function getCollectList()
    {
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请登录');
        }
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 10);
        $post_ids = ModelCollect::where('user_id', $user_id)->column('post_id');
        $list = Post::where('id', 'in', $post_ids)->field('id,name,image')
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->each(function ($item) {
                $item['image'] = cdnurl($item['image'], true);
            });
        $this->success('获取成功', $list);
    }
    /**
     * 添加收藏
     */
    public function addCollect()
    {
        $post_id = $this->request->param('post_id/d');
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请登录');
        }
        $post = Post::get($post_id);
        if (!$post) {
            $this->error('帖子不存在');
        }
        $collect = ModelCollect::where(['user_id' => $user_id, 'post_id' => $post_id])->find();
        if ($collect) {
            $this->error('已收藏');
        }
        $collect = new ModelCollect();
        $collect->user_id = $user_id;
        $collect->post_id = $post_id;
        $collect->save();
        $this->success('收藏成功');
    }
    /**
     * 取消收藏
     */
    public function cancelCollect()
    {
        $post_id = $this->request->param('post_id/d');
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请登录');
        }
        $collect = ModelCollect::where(['user_id' => $user_id, 'post_id' => $post_id])->find();
        if (!$collect) {
            $this->error('未收藏');
        }
        $collect->delete();
        $this->success('取消成功');
    }
    /**
     * 收藏状态
     */
    public function getCollectStatus()
    {
        $post_id = $this->request->param('post_id/d',0);
        if (!$post_id) {
            $this->error('参数错误');
        }
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请登录');
        }
        $collect = ModelCollect::where(['user_id' => $user_id, 'post_id' => $post_id])->find();
        if ($collect) {
            $this->success('已收藏', true);
        } else {
            $this->success('未收藏', false);
        }
    }
}
